local colshape = createColCuboid ( -180.76, 1158.14, 18, 55.2, 30.3, 5 )
local marker = createMarker(-139.22,1184,19,"cylinder",3,255,0,0,60)
createBlip( -139.22,1184,19, 55)

function hit(el,md)
    if not md or getElementType(el) ~= "player" then return end
    if not isPedInVehicle(el) then return end
    if getElementData(getPedOccupiedVehicle(el), 'vehicle:gielda') then return end
        if getElementData(getPedOccupiedVehicle(el), 'vehicle:data') then
        triggerClientEvent(el,'cmta_gielda:showGUI',resourceRoot)
        else
            exports['cmta-notyfikacje']:sendNotification(el,"#FF0000Wykryto nieprawidłowość!\n#ffffffNie możesz wystawić tego pojazdu.","error",4000)
        end
    end
addEventHandler( "onMarkerHit", marker, hit)

function leave(el,md)
    if not md or getElementType(el) ~= "player" then return end
        triggerClientEvent(el,'cmta_gielda:hideGUI',resourceRoot)
    end
addEventHandler( "onMarkerLeave", marker, leave)

addEventHandler("onColShapeLeave", colshape, function(plr,md)
	if (not md) then return end
    if getElementType(plr) == "vehicle" then
    local data = getElementData(plr, "vehicle:gielda")
    if data then
	local colshape = data.value20
    local marker = data.value21
	setElementData(plr,"vehicle:gielda",nil)
	    if isElement(colshape) then
	        destroyElement(colshape)
        end
        if isElement(marker) then
            destroyElement(marker)
        end
    end
end
end)


addEventHandler ( "onResourceStart", getRootElement(), function()

for i,v in pairs (getElementsByType("vehicle")) do
    if getElementData(v,"vehicle:gielda") then
        local data = getElementData(v,"vehicle:gielda")
        local x,y,z = getElementPosition(v)
        col = createColSphere(x,y,z, 1.5)
        attachElements ( col, v, 0, 2.5, 0 )
    
        carmarker=createMarker(x,y,z+0.8, "cylinder", 2, 100, 0, 255,0)
        setElementData(carmarker, 'marker:data', {name='', icon='sell',size=1})
        attachElements ( carmarker, v, 0, 0, 1 )
        data.value20 = col
        data.value21 = carmarker
        setElementData(v, 'vehicle:gielda', data)



    end
end

function znajdzprzezuid(uid)
    if not uid then return end
	for _,p in pairs(getElementsByType('player'),root,false) do
		if getElementData(p,"player:data").uid and getElementData(p,"player:data").uid == uid then return p end
	end
	return false
end

end)

addEvent("cmta_gielda:buy_vehicle", true)
addEventHandler("cmta_gielda:buy_vehicle", resourceRoot, function(veh)
    if tonumber(getElementData(client,"player:data").uid) == tonumber(getElementData(veh,"vehicle:gielda").value4) then
        exports['cmta-notyfikacje']:sendNotification("#FF0000Wykryto nieprawidłowość!\n#ffffffNie możesz kupić swojego pojazdu.","error",3000)
    return 
    end
    if tonumber(getElementData(client,"player:data").points) < tonumber(getElementData(veh,"vehicle:gielda").value13) then
        exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffNie posiadasz tyle punktów.","error",3000)
    return 
    end
    local q=exports["cmta-db"]:dbGet("select * from cmta_pojazdy where ownedPlayer=?", getElementData(client,"player:data").uid)
  --  if getElementData(client,"player:data") and getElementData(client,"player:data").limitveh <= tonumber(#q) then
  --      exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffPosiadasz już limit pojazdów.","error",3000)
  --  return
  --  end
    local veh_data = getElementData(veh,"vehicle:data")
    local plr_data = getElementData(client,"player:data")
    plr_data.points = ((getElementData(client,"player:data").points)-tonumber(getElementData(veh,"vehicle:gielda").value13))
    veh_data.ownedPlayer = getElementData(client,"player:data").uid
    setElementData(veh,"vehicle:data",veh_data)
    setElementData(client,"player:data",plr_data)

    local online=znajdzprzezuid(getElementData(veh,"vehicle:gielda").value4)
    if online then
        local seller_data = getElementData(online,"player:data")
        seller_data.points = ((getElementData(online,"player:data").points)+tonumber(getElementData(veh,"vehicle:gielda").value13)*getElementData(veh,"vehicle:gielda").value22)
        setElementData(online,"player:data",seller_data)
        exports['cmta-notyfikacje']:sendNotification(online,"#00ff00Świetna Informacja!\n#ffffffTwój pojazd marki "..getVehicleName(veh).."[ID:"..getElementData(veh,"vehicle:gielda").value2.."] sprzedał się,\nOtrzymujesz "..(tonumber(getElementData(veh,"vehicle:gielda").value13)*getElementData(veh,"vehicle:gielda").value22).." punktów.","success",7000)

    else
        exports['cmta-db']:dbSet("UPDATE cmta_users SET points=? WHERE id=?", ((getElementData(client,"player:data").points)+tonumber(getElementData(veh,"vehicle:gielda").value13)*getElementData(veh,"vehicle:gielda").value22), getElementData(client,"player:data").uid)
    end

    exports["cmta-db"]:dbSet("INSERT INTO cmta_logs_vehicles SET vehid=?, nameowner=?, idowner=?, operation=?, time=NOW()", getElementData(veh,"vehicle:gielda").value2, getPlayerName(client):gsub("#%x%x%x%x%x%x",""),getElementData(client,"player:data").uid,"Zakup pojazdu na giełdzie za "..(getElementData(veh,"vehicle:gielda").value13).." punktów.")
    exports['cmta-db']:dbSet("UPDATE cmta_pojazdy SET ownedPlayer=? WHERE id=?", getElementData(client,"player:data").uid, getElementData(veh,"vehicle:gielda").value2)
    exports['cmta-notyfikacje']:sendNotification(client,"#00ff00Sukces!\n#ffffffPomyślnie zakupiłeś pojazd.","success",5000)

    local data = getElementData(veh, "vehicle:gielda")
    if data then
	local colshape = data.value20
    local marker = data.value21
	setElementData(veh,"vehicle:gielda",nil)
	    if isElement(colshape) then
	        destroyElement(colshape)
        end
        if isElement(marker) then
            destroyElement(marker)
        end
    end

    triggerClientEvent(client,'cmta_gielda:hide_info',resourceRoot)
end)










local pjVehs = {
    "445",
    "429",
    "424",
    "496",
    "422",
    "541",
    "415",
    "542",
    "589",
    "579",
    "400",
    "500",
    "418",
    "516",
    "404",
    "458",
    "439",
    "506",
    "566",
    "549",
    "576",
    "451",
    "540",
    "478",
    "529",
    "555",
    "477",
    "600",
    "558",
    "527",
    "543",
    "554",
    "565",
    "474",
    "545",
    "410",
    "495",
}


addEvent("cmta_gielda:addVehicle", true)
addEventHandler("cmta_gielda:addVehicle", resourceRoot, function(price)
    local veh = getPedOccupiedVehicle(client)
    local data = getElementData(veh, "vehicle:data")
    local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_pojazdy WHERE id=?", data.id)
    local resultprice=exports["cmta-db"]:dbGet("SELECT * FROM cmta_carshowroom WHERE id=?", getElementModel(veh))
    if resultprice and #resultprice > 0 then
        salon_koszt = resultprice[1]["price"]
    else
        salon_koszt = "#ff0000Niedostępny w salonie"
    end

    for i,v in pairs(pjVehs) do
        if tonumber(v) ~= getElementModel(getPedOccupiedVehicle(client)) then
        vehicle_paintjob = "#00ff00Możliwość malowania"
        else
        vehicle_paintjob = "#ff2828Brak możliwości malowania"
        end
    end

    if result[1]["mk1"] == 1 then
        update1 = "MK1,"
    else
        update1 = ""
    end

    if result[1]["mk2"] == 1 then
        update2 = "MK2,"
    else
        update2 = ""
    end

    if result[1]["mk3"] == 1 then
        update3 = "MK3,"
    else
        update3 = ""
    end

    if result[1]["launchcontrol"] == 1 then
        update4 = "LaunchControl,"
    else
        update4 = ""
    end

    if result[1]["asr"] == 1 then
        update5 = "ASR,"
    else
        update5 = ""
    end

    if result[1]["sterringLock"] == 1 then
        update6 = "Regulacja Kątu Skrętu"
    else
        update6 = ""
    end

    if getElementData(client,"player:data").vip then
        podatek_od_sprzedazy = 1
    else
        podatek_od_sprzedazy = 0.97
    end

    realTime=getRealTime()
	local r = realTime.year+1900
	local m = realTime.month+1
	local t = realTime.monthday
	local czas=string.format("%04d-%02d-%02d %02d:%02d:%02d", r, m, t,realTime.hour, realTime.minute, realTime.second)
    
    local x,y,z = getElementPosition(veh)
    car_col = createColSphere(x,y,z, 1.5)
    attachElements ( car_col, veh, 0, 2.5, 0 )

    carmarker=createMarker(x,y,z+0.8, "cylinder", 2, 100, 0, 255,0)
    setElementData(carmarker, 'marker:data', {name='', icon='sell',size=1})
    attachElements ( carmarker, veh, 0, 0, 1 )


    setElementData(veh, "vehicle:gielda", {
    value1 = getVehicleName(veh),
    value2 = data.id,
    value3 = getPlayerName(client),
    value4 = getElementData(client,"player:data").uid,
    value5 = salon_koszt,
    value6 = data.mileage,
    value7 = result[1]["driveType"],
    value8 = result[1]["engine"],
    value9 = result[1]["engineType"],
    value10 = vehicle_paintjob,
    value11 = result[1]["tank"],
    value12 = czas,
    value13 = price,
    value14 = update1,
    value15 = update2,
    value16 = update3,
    value17 = update4,
    value18 = update5,
    value19 = update6,
    value20 = car_col,
    value21 = carmarker,
    value22 = podatek_od_sprzedazy
    })

    exports['cmta-notyfikacje']:sendNotification(client,"#00ff00Udało się!\n#ffffffPomyślnie wystawiłeś pojazd\nna sprzedaż.","success",4000)
    triggerClientEvent(client,'cmta_gielda:hideGUI',resourceRoot)

end)

addEventHandler("onColShapeHit",resourceRoot,function(plr)
    if source ~= colshape then
    for i,v in pairs (getElementsByType("vehicle")) do
    if getElementData(v,"vehicle:gielda") and source == getElementData(v,"vehicle:gielda").value20 then
        triggerClientEvent( plr, "cmta_gielda:show_info", resourceRoot, v)
    else
    end
end
end
end)

addEventHandler("onColShapeLeave",resourceRoot,function(plr)
    if source ~= colshape then
    for i,v in pairs (getElementsByType("vehicle")) do
    if getElementData(v,"vehicle:gielda") and source == getElementData(v,"vehicle:gielda").value20 then
        triggerClientEvent( plr, "cmta_gielda:hide_info", resourceRoot)
    else
    end
end
end
end)